// 简单版的数据库

/*
    曾
    删
    改
    查
*/
class Store {
    constructor(data = []) {
        this.store = {
            data: [],
            map: new Map()
        }
        this.store = data.reduce((res, item, index) => {
            res.data.push(item)
            res.map.set(item.id, index)
            return res
        }, {
            data: [],
            map: new Map()
        })
    }
    push(data) {
        if (this.store.map.get(data.id) === undefined) {
            this.store.data.push(data)
            this.store.map.set(
                data.id,
                this.store.data.length - 1
            )
            return true
        }
        return false
    }
    delete(data) {
        let index = this.store.data.findIndex(v => v.id === data.id)
        console.log('delete index: ', index, this.store.map);
        if (index !== undefined) {
            this.store.data.splice(index, 1);
            this.store.map.delete(data.id)
            return true
        }
        return false
    }
    update(data) {
        let index = this.store.map.get(data.id)
        if (index !== undefined) {
            this.store.data[index] = data
            return true
        }
        return false
    }
    query() {
        return this.store.data
    }
}

module.exports = Store
